package com.czxy.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //1.初始化 Spring 容器
        AnnotationConfigWebApplicationContext applicationContext  = new AnnotationConfigWebApplicationContext();

        //整合SpringMVC
        applicationContext.register(SpringMVCConfig.class);
        //整合Spring
        applicationContext.register(SpringConfig.class);
        //整合Mybatis
        applicationContext.register(MyBatisConfig.class);

        applicationContext.setServletContext(servletContext);

        //2.设置核心控制器
        ServletRegistration.Dynamic ds = servletContext.addServlet("springmvc", new DispatcherServlet(applicationContext));
        ds.addMapping("*.action");
        ds.setLoadOnStartup(2);


        //3 post乱码配置
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8"));
        encodingFilter.addMappingForUrlPatterns(null, true, "/*");

    }
}
